<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<link rel="stylesheet" href="css/bootstrap-3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="css/register.css" />
<link rel="stylesheet" href="css/listCommon.css" />
<link rel="stylesheet" href="css/evaluation.css" />
<style>
    .modal-backdrop {
        position: inherit;
    }
    #jstree_div::-webkit-scrollbar, #relateListDiv::-webkit-scrollbar{
        width:10px;
        height:10px;
    }
</style>
<jsp:include page="../common/nav.jsp"></jsp:include>
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="purchaseOrder">
        <input id="id" name="id" type="hidden" value="${requestScope.purchasingRequisition.id}">
        <div class="formTitle">采购申请单信息</div>
        <div class="trackInfomation">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <span>*</span>
                        <label>标题：</label>
                        <input id="title" name="title" type="text" class="form-control" placeholder="请输入标题" value="${requestScope.purchasingRequisition.title}">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <span id="">*</span>
                        <label>采购类型：</label>
                        <select id="type" name="type" class="form-control">
                            <option value="">请选择采购类型</option>
                            <c:forEach items="${requestScope.typeMap}" var="typeMap">
                                <c:if test="${typeMap.key == requestScope.purchasingRequisition.type}">
                                    <option value="${typeMap.key}" selected>${typeMap.value}</option>
                                </c:if>
                                <c:if test="${typeMap.key != requestScope.purchasingRequisition.type}">
                                    <option value="${typeMap.key}">${typeMap.value}</option>
                                </c:if>
                            </c:forEach>
                        </select>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <span>*</span>
                        <label>期望交货时间：</label>
                        <input id="scheduledTime" name="scheduledTime" type="date" class="form-control" value="${requestScope.purchasingRequisition.scheduledTime}">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <span>*</span>
                        <label>采购原因：</label>
                        <input id="reason" name="reason" type="text" class="form-control" placeholder="请输入采购原因" value="${requestScope.purchasingRequisition.reason}">
                    </div>
                </div>
                <div class="col-md-12">
                    <div class="form-group">
                        <span>&nbsp;&nbsp;</span>
                        <label class="fuyanText">附言(摘要)：</label>
                        <textarea id="remark" name="remark" class="form-control fuyan" rows="3" placeholder="请输入附言" style="margin-left: 0;height:80px !important;">${requestScope.purchasingRequisition.remark}</textarea>
                    </div>
                </div>
            </div>
        </div>
        <div class="formTitle">采购人信息</div>
        <div class="trackInfomation">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label>申请人：</label>
                        <input id="createUserName" type="text" class="form-control" value="${requestScope.purchasingRequisition.createUserName}" readonly>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label>公司代码：</label>
                        <input id="companyCode" name="companyCode" type="text" class="form-control" value="${requestScope.purchasingRequisition.companyCode.concat(' - '.concat(requestScope.purchasingRequisition.companyName))}" readonly>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label>申请部门：</label>
                        <input id="departmentCode" name="departmentCode" type="hidden" value="${requestScope.purchasingRequisition.departmentCode}">
                        <input id="departmentName" name="departmentName" type="text" class="form-control" value="${requestScope.purchasingRequisition.departmentName}" readonly>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label>电子邮箱：</label>
                        <input id="mailbox" type="text" class="form-control" value="${requestScope.purchasingRequisition.mailbox}" readonly>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label>手机号码：</label>
                        <input id="tel" type="text" class="form-control" placeholder="请输入手机号码" value="${requestScope.purchasingRequisition.tel}">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label>固定电话：</label>
                        <input id="landLine" type="text" class="form-control" value="${requestScope.purchasingRequisition.landLine}" readonly>
                    </div>
                </div>
                <div class="col-md-12">
                    <div class="form-group">
                        <label class="fuyanText">收货地址：</label>
                        <textarea id="address" name="address" class="form-control fuyan" rows="3" placeholder="请输入收货地址" style="margin-left: 0;height:80px !important;">${requestScope.purchasingRequisition.address}</textarea>
                    </div>
                </div>
            </div>
        </div>
        <div class="formTitle">
            物资信息
            <button type="button" class="btn  addMetarial" data-toggle="modal" data-target="#addMetarial">添加物资</button>
        </div>
        <div class="tableWrap">
            <table class="table table-bordered">
                <thead id="subBody">
                    <tr>
                        <th width="5%">序号</th>
                        <th>物料编码</th>
                        <th>品牌</th>
                        <th>物资名称</th>
                        <th>型号</th>
                        <th>类目</th>
                        <th>数量</th>
                        <th>单位</th>
                        <th width="10%">附件</th>
                        <th>状态</th>
                        <th width="20%">附言</th>
                        <th width="10%">操作</th>
                    </tr>
                    <c:if test="${empty requestScope.purchasingRequisition.subs}">
                        <tr id="nothing">
                            <td colspan="12" style="color: #bbbbbb">无物资信息</td>
                        </tr>
                    </c:if>
                    <c:if test="${not empty requestScope.purchasingRequisition.subs}">
                        <c:forEach items="${requestScope.purchasingRequisition.subs}" var="sub" varStatus="index">
                            <tr id="${"materialLine".concat(index.count)}">
                                <td id="${"materialNo".concat(index.count)}">${index.count}</td>
                                <td id="${"detailId".concat(index.count)}" style="display: none">${sub.id}</td>
                                <td id="${"materialId".concat(index.count)}" style="display: none">${sub.materialId}</td>
                                <td id="${"materialCode".concat(index.count)}">${sub.materialCode}</td>
                                <td id="${"materialBrand".concat(index.count)}">${sub.materialBrand}</td>
                                <td id="${"materialName".concat(index.count)}">${sub.materialName}</td>
                                <td id="${"materialModel".concat(index.count)}">${sub.materialModel}</td>
                                <td id="${"materialCategory".concat(index.count)}">${sub.materialCategory}</td>
                                <td><input id="${"quantity".concat(index.count)}" type="number" style="border:1px solid #ddd;width:60px;border-radius:4px;" value="${sub.quantity}"></td>
                                <td id="${"materialUnit".concat(index.count)}">${sub.materialUnit}</td>
                                <c:if test="${'' == sub.accessory}">
                                    <td id="${"subFilePath".concat(index.count)}" style="display: none"></td>
                                    <td id="${"subFileTd".concat(index.count)}"><input id="${"subFile".concat(index.count)}" type="file"></td>
                                </c:if>
                                <c:if test="${'' != sub.accessory}">
                                    <td id="${"subFilePath".concat(index.count)}">
                                        <a style="text-decoration: none; color: black" download="${sub.accessoryName}" href="${sub.accessory}">${sub.accessoryName}</a>
                                        <a style="float: right;color:red; cursor: pointer;" onclick="clearSubFile(${index.count})">X</a>
                                    </td>
                                    <td id="${"subFileTd".concat(index.count)}" style="display: none"><input id="${"subFile".concat(index.count)}" type="file"></td>
                                </c:if>
                                <td id="${"subStatus".concat(index.count)}" style="display: none">${sub.status}</td>
                                <td id="${"subStatusText".concat(index.count)}">${requestScope.subStatusMap[sub.status]}</td>
                                <td><input id="${"subRemark".concat(index.count)}" type="text" style="border:1px solid #ddd;width:100%;border-radius:4px;" value="${sub.remark}"></td>
                                <td id="${"materialOperation".concat(index.count)}" class="attachment">
                                    <button id="materialUpload' + subSize + '" type="button" style="margin-left: 3px" onclick="uploadMaterial(${index.count})">上传附件</button>
                                    <button id="${"materialDel".concat(index.count)}" type="button" style="margin-left: 3px" onclick="delMaterial(${index.count})">删除</button>
                                </td>
                            </tr>
                        </c:forEach>
                    </c:if>
                </thead>
            </table>
        </div>
        <div class="formTitle">
            附件信息
            <button type="button" class="btn  addMetarial" data-toggle="modal" data-target="#addFile">添加附件</button>
        </div>
        <div class="tableWrap">
            <table class="table table-bordered">
                <thead id="fileBody">
                <tr>
                    <th width="5%">序号</th>
                    <th>附件名称</th>
                    <th width="10%">操作</th>
                </tr>
                <c:if test="${empty requestScope.purchasingRequisition.accessory}">
                    <tr id="fileNothing">
                        <td colspan="3" style="color: #bbbbbb">无附件信息</td>
                    </tr>
                </c:if>
                <c:if test="${not empty requestScope.purchasingRequisition.accessory}">
                    <c:forEach items="${requestScope.purchasingRequisition.fileMap}" var="file" varStatus="index">
                        <tr id="${"fileLine".concat(index.count)}">
                            <td id="${"fileNo".concat(index.count)}">${index.count}</td>
                            <td id="${"fileName".concat(index.count)}">
                                <a style="text-decoration: none; color: black" download="${file.value}" href="${file.key}">${file.value}</a>
                            </td>
                            <td id="${"fileOperation".concat(index.count)}" class="attachment">
                                <button id="${"fileDel".concat(index.count)}" type="button" onclick="delFile(${index.count}, '${file.key}')">删除</button>
                            </td>
                        </tr>
                    </c:forEach>
                </c:if>
                </thead>
            </table>
        </div>
        <div class="trackSubmit">
            <button type="button" onclick="save()">保存</button>
            <button type="button" onclick="window.location.href='web/purchasingRequisition/getPageList'">返回</button>
        </div>
    </div>
</div>
<div class="modal fade" id="addMetarial" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content" style="padding: 0 20px">
            <div class="modal-header">
                <h4 class="modal-title" id="myModalLabel">添加物资</h4>
            </div>
            <div class="modal-body">
                <div class="col-sm-4">
                    <div class="ibox ">
                        <div class="ibox-content border-bottom">
                            <div class="input-group col-sm-12">
                                <div class="input-group-addon bg-info">
                                    <i class="fa fa-search"></i>
                                </div>
                                <input style="width:120px;" type="text" class="form-control" id="searchTree" placeholder="输入查询条件...">
                            </div>
                            <div class="hr-line-dashed"></div>
                            <div id="jstree_div" style="height:500px;overflow-y: scroll;"></div>
                        </div>
                    </div>
                </div>
                <div id="relateListDiv" class="col-sm-8" style="clear:none;max-height:600px;overflow-y: scroll;"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="addSub()">确定</button>
            </div>
        </div>

    </div>
</div>
<div class="modal fade" id="addFile" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content" style="padding: 0 20px">
            <div class="modal-header">
                <h4 class="modal-title">添加附件</h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-12">
                        <div class="upload-wrap">
                            <input id="file" type="file" />
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="saveFile()">上传</button>
                <button type="button" class="btn btn-default" onclick="closePopout();">关闭</button>
            </div>
        </div>
    </div>
</div>
<script src="css/bootstrap-3.3.7/js/jquery-2.1.4.min.js" type="text/javascript" charset="utf-8"></script>
<script src="css/bootstrap-3.3.7/js/bootstrap.js" type="text/javascript" charset="utf-8"></script>
<script src="js/plugins/jsTree/jstree.min.js"></script>
<link href="css/plugins/jsTree/style.min.css" rel="stylesheet">
<script>

    var delIds = [];
    var subSize = ${requestScope.purchasingRequisition.id != null} ? "${requestScope.purchasingRequisition.subs.size()}" : 0;
    var fileList = ${requestScope.purchasingRequisition.id != null} && ${not empty requestScope.purchasingRequisition.accessory}
        ? "${requestScope.purchasingRequisition.accessory}".split("FILE_NAME_END")
        : [];

    // 添加物资
    function addSub(){
        if (selected.length != 0) {
            $("#nothing").remove();
            for (let i = 0; i < selected.length; i ++) {
                subSize ++;
                $("#subBody").append(
                    '<tr id="materialLine' + subSize + '">' +
                        '<td id="materialNo' + subSize + '">' + subSize + '</td>' +
                        '<td id="detailId' + subSize + '" style="display: none">-1</td>' +
                        '<td id="materialId' + subSize + '" style="display: none">' + $("#materialId" + selected[i]).text() + '</td>' +
                        '<td id="materialCode' + subSize + '">' + $("#materialCode" + selected[i]).text() + '</td>' +
                        '<td id="materialBrand' + subSize + '">' + $("#materialBrand" + selected[i]).text() + '</td>' +
                        '<td id="materialName' + subSize + '">' + $("#materialName" + selected[i]).text() + '</td>' +
                        '<td id="materialModel' + subSize + '">' + $("#materialModel" + selected[i]).text() + '</td>' +
                        '<td id="materialCategory' + subSize + '">' + $("#materialCategory" + selected[i]).text() + '</td>' +
                        '<td><input style="border:1px solid #ddd;width:60px;border-radius:4px;" id="quantity' + subSize + '" type="number"></td>' +
                        '<td id="materialUnit' + subSize + '">' + $("#materialUnit" + selected[i]).text() + '</td>' +
                        '<td id="subFilePath' + subSize + '" style="display: none"></td>' +
                        '<td id="subFileTd' + subSize + '"><input id="subFile' + subSize + '" type="file"></td>' +
                        '<td id="subStatus' + subSize + '" style="display: none">0</td>' +
                        '<td id="subStatusText' + subSize + '">${requestScope.subStatusMap["0"]}</td>' +
                        '<td><input style="border:1px solid #ddd;width:100%;border-radius:4px;" id="subRemark' + subSize + '" type="text"></td>' +
                        '<td id="materialOperation' + subSize + '" class="attachment">' +
                            '<button id="materialUpload' + subSize + '" type="button" style="margin-left: 3px" onclick="uploadMaterial(' + subSize + ')">上传附件</button>' +
                            '<button id="materialDel' + subSize + '" type="button" style="margin-left: 3px" onclick="delMaterial(' + subSize + ')">删除</button>' +
                        '</td>' +
                    '</tr>'
                );
            }
        }
        $('div:last').remove();
        $("#addMetarial").modal('hide').removeClass("show");
    }

    // 上传物资附件
    function uploadMaterial(index) {
        let files = $('#subFile' + index)[0].files;
        if (files.length > 0) {
            let formData = new FormData();
            for(let i = 0; i < files.length; i ++){
                if (files[i].size > 1048576) {
                    redragonJS.alert("文件过大,无法上传!");
                    return;
                }
                formData.append("accessory", files[i]);
            }
            $.ajax({
                type: 'post',
                url: "web/purchasingRequisition/upload",
                data: formData,
                dataType: "json",
                cache: false,
                processData: false,
                contentType: false,
                async: false,
                success: function (data) {
                    if (data.length > 0) {
                        $("#subFilePath" + index).html(
                            '<a style="text-decoration: none; color: black" download="' + data[0].name + '" href="' + data[0].url + '">' + data[0].name + '</a>' +
                            '<a style="float: right;color:red; cursor: pointer;" onclick="clearSubFile(' + index + ')">X</a>'
                        ).removeAttr("style");
                        $("#subFile" + index).val("");
                        $("#subFileTd" + index).attr("style", "display:none;")
                    } else {
                        redragonJS.alert("上传失败!");
                    }
                }
            });
        }
    }

    // 删除物资附件
    function clearSubFile(index) {
        $("#subFilePath" + index).html("").attr("style", "display:none;");
        $("#subFileTd" + index).removeAttr("style")
    }

    // 删除物资信息
    function delMaterial(index) {
        let id = $("#detailId" + index).text();
        if (id != "-1") {
            delIds.push(id);
        }
        $("#materialLine" + index).remove();
        if (index < subSize) {
            for (var i = index + 1; i <= subSize; i ++) {
                let num = i - 1;
                $("#materialLine" + i).attr("id", "materialLine" + num);
                $("#materialNo" + i).text(num).attr("id", "materialNo" + num);
                $("#detailId" + i).attr("id", "detailId" + num);
                $("#materialId" + i).attr("id", "materialId" + num);
                $("#materialCode" + i).attr("id", "materialCode" + num);
                $("#materialBrand" + i).attr("id", "materialBrand" + num);
                $("#materialName" + i).attr("id", "materialName" + num);
                $("#materialModel" + i).attr("id", "materialModel" + num);
                $("#materialCategory" + i).attr("id", "materialCategory" + num);
                $("#quantity" + i).attr("id", "quantity" + num);
                $("#materialUnit" + i).attr("id", "materialUnit" + num);
                $("#subFilePath" + i).attr("id", "subFilePath" + num);
                $("#subFileTd" + i).attr("id", "subFileTd" + num);
                $("#subFile" + i).attr("id", "subFile" + num);
                $("#subStatus" + i).attr("id", "subStatus" + num);
                $("#subStatusText" + i).attr("id", "subStatusText" + num);
                $("#subRemark" + i).attr("id", "subRemark" + num);
                $("#materialOperation" + i).attr("id", "materialOperation" + num);
                $("#materialUpload" + i).attr("id", "materialUpload" + num).attr("onclick", "uploadMaterial(" + num + ")");
                $("#materialDel" + i).attr("id", "materialDel" + num).attr("onclick", "delMaterial(" + num + ")");
            }
        }
        if (-- subSize == 0) {
            $("#subBody").append(
                '<tr id="nothing">' +
                    '<td colspan="12" style="color: #bbbbbb">无物资信息</td>' +
                '</tr>'
            );
        }
    }

    // 上传附件
    function saveFile() {
        let files = $('#file')[0].files;
        if (files.length == 0) {
            redragonJS.alert("请添加需要上传的文件");
        } else {
            let formData = new FormData();
            for(let i = 0; i < files.length; i ++){
                if (files[i].size > 1048576) {
                    redragonJS.alert("文件过大,无法上传!");
                    return;
                }
                formData.append("accessory", files[i]);
            }
            $.ajax({
                type: 'post',
                url: "web/purchasingRequisition/upload",
                data: formData,
                dataType: "json",
                cache: false,
                processData: false,
                contentType: false,
                async: true,
                success: function (data) {
                    if (data.length > 0) {
                        showAccessory(data);
                    } else {
                        redragonJS.alert("上传失败!");
                    }
                }
            });
        }
    }

    // 回显附件
    function showAccessory(data) {
        $("#fileNothing").remove();
        let html = "";
        for (let i = 0; i < data.length; i ++) {
            let url = data[i].url;
            fileList.push(url);
            let j = fileList.length;
            html +=
                '<tr id="fileLine' + j + '">' +
                    '<td id="fileNo' + j + '">' + j + '</td>' +
                    '<td id="fileName' + j + '">' +
                        '<a style="text-decoration: none; color: black" download="' + data[i].name +  '" href="' + url + '"> ' + data[i].name + '</a>' +
                    '</td>' +
                    '<td id="fileOperation' + j + '" class="attachment">' +
                    '<button id="fileDel' + j + '" type="button" onclick="delFile(' + j +  ',\'' + url + '\')">删除</button>' +
                    '</td>' +
                '</tr>';
        }
        $("#fileBody").append(html);
        closePopout();
    }

    // 清空弹框数据并隐藏弹框
    function closePopout() {
        $("#file").val("");
        $('div:last').remove();
        $("#addFile").modal('hide').removeClass("show");
    }

    // 删除附件
    function delFile(index, url) {
        $("#fileLine" + index).remove();
        if (index < fileList.length) {
            for (var i = index + 1; i <= fileList.length; i ++) {
                let num = i - 1;
                $("#fileLine" + i).attr("id", "fileLine" + num);
                $("#fileNo" + i).text(num).attr("id", "fileNo" + num);
                $("#fileName" + i).attr("id", "fileName" + num);
                $("#fileOperation" + i).attr("id", "fileOperation" + num);
                $("#fileDel" + i).attr("id", "fileDel" + num).attr("onclick", "delFile(" + num + "," + $('#fileUrl' + i).text() + ")");
            }
        }
        fileList.splice(fileList.indexOf(url), 1);
        if (fileList.length == 0) {
            $("#fileBody").append(
                '<tr id="fileNothing">' +
                    '<td colspan="3" style="color: #bbbbbb">无附件信息</td>' +
                '</tr>'
            );
        }
    }

    // 保存
    function save() {
        if ($("#title").val().trim() == "") {
            redragonJS.alert("标题不能为空");
        } else if ($("#type").val() == "") {
            redragonJS.alert("采购类型不能为空");
        } else if ($("#scheduledTime").val() == "") {
            redragonJS.alert("期望交货时间不能为空");
        } else if ($("#reason").val().trim() == "") {
            redragonJS.alert("采购原因不能为空");
        } else if ($("#address").val().trim() == "") {
            redragonJS.alert("收货地址不能为空");
        } else if (subSize == 0) {
            redragonJS.alert("请添加物资信息");
        } else {
            for (let i =1; i <= subSize; i ++) {
                let num = $("#quantity" + i).val();
                if (num == "") {
                    redragonJS.alert("请输入序号为:" + i + "的物资的数量!");
                    return;
                } else if (num <= 0) {
                    redragonJS.alert("序号为:" + i + "的物资的数量必须大于0!");
                    return;
                } else if (num % 1 != 0) {
                    redragonJS.alert("序号为:" + i + "的物资的数量必须为整数!");
                    return;
                }
            }
            $.ajax({
                url : "web/purchasingRequisition/save",
                contentType : "application/json",
                dataType : 'json',
                data : JSON.stringify(getSubmitInfo()),
                type:'post',
                async : true,
                success : function(data) {
                    if(data.code == 1) {
                        redragonJS.alert("操作成功!");
                        setTimeout(function(){
                            window.location.href='web/purchasingRequisition/getPageList'
                        },1000);
                    } else {
                        redragonJS.alert(data.msg);
                    }
                }
            });
        }
    }

    // 获取提交数据
    function getSubmitInfo() {
        let data = {};
        data.id = $("#id").val();
        data.title = $("#title").val();
        data.type = $("#type").val();
        data.companyCode = "${requestScope.purchasingRequisition.companyCode}";
        data.companyName = "${requestScope.purchasingRequisition.companyName}";
        data.departmentCode = $("#departmentCode").val();
        data.departmentName = $("#departmentName").val();
        data.createUserName = $("#createUserName").val();
        data.tel = $("#tel").val();
        data.landLine = $("#landLine").val();
        data.mailbox = $("#mailbox").val();
        data.scheduledTime = $("#scheduledTime").val();
        data.reason = $("#reason").val();
        data.address = $("#address").val();
        data.accessory = getAccessory();
        data.remark = $("#remark").val();
        data.ids = delIds;
        let subs = [];
        for(var i = 1; i <= subSize; i ++){
            let sub = {};
            sub.id = $("#detailId" + i).text();
            sub.materialId = $("#materialId" + i).text();
            sub.materialCode = $("#materialCode" + i).text();
            sub.materialBrand = $("#materialBrand" + i).text();
            sub.materialName = $("#materialName" + i).text();
            sub.materialModel = $("#materialModel" + i).text();
            sub.materialCategory = $("#materialCategory" + i).text();
            sub.quantity = $("#quantity" + i).val();
            sub.materialUnit = $("#materialUnit" + i).text();
            sub.accessory = $("#subFilePath" + i + " a:first-child").attr("href");
            sub.remark = $("#subRemark" + i).val();
            subs.push(sub);
        }
        data.subs = subs;
        return data;
    }

    // 获取附件字符串
    function getAccessory() {
        if (fileList.length == 0) {
            return "";
        } else {
            let result = fileList[0];
            for (let i = 1; i < fileList.length; i ++) {
                result += "FILE_NAME_END" + fileList[i];
            }
            return result;
        }
    }

    $('#jstree_div').jstree({
        'core' : {
            "themes" : {
                "stripes" : false,//背景是否显示间纹
                "dots": false,//是否显示树连接线
                "icons": true,//是否显示节点的图标
                "ellipsis": true,//节点名过长时是否显示省略号
            },
            'multiple' : false,  // 可否多选
            'dblclick_toggle': true,   //允许tree的双击展开
            'expand_selected_onload': false,
            'data' : {
                'url': 'web/mdMaterialCategory/getMdMaterialCategoryTreeData',
                'dataType': 'json',
                'data': function (node) { // 传给服务端点击的节点
                    return { 'nodeId': node.id };
                },
                success: function (data) {
                    if(data.id==""){
                        $("#jstree_div").html("");
                    }else{
                        $("#addRootButton").hide();
                    }
                }
            },
            "check_callback" : true,
        },
        'plugins': ["state",'types','themes','search','unique','changed'],
        "types" : {
            "default" : {
                'icon' : 'fa fa-folder'
            },
            "root" : {
                "icon" : 'fa fa-home fa-lg',
            },
            "node" : {
                'icon' : 'fa fa-folder'
            },
        },
        'checkbox': {
            'tie_selection': false,
            'keep_selected_style': true,
            'whole_node': false,
            'three_state': false,
        }
    }).on('click.jstree', function(event) {
        getRelateListAjax(getTreeSelectNodeId(),null);
    });

    //ajax获取关联列表
    function getRelateListAjax(id,page){
        redragonJS.loading("relateListDiv");
        $.ajax({
            type: "post",
            url: "web/mdMaterialCategory/getMdMaterialCategory",
            data: {"categoryId": id},
            async: false,
            dataType: "json",
            cache: false,
            success: function(data){
                if(data!=""){
                    $.ajax({
                        type: "post",
                        url: "web/other/getMaterialList",
                        data: {"categoryCode": data.categoryCode,"page":page==null?1:page},
                        async: false,
                        dataType: "html",
                        cache: false,
                        success: function(data){
                            redragonJS.removeLoading("relateListDiv");
                            if(data!=""){
                                $("#relateListDiv").html(data);
                            }
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown){
                            redragonJS.alert(textStatus);
                        }
                    });
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                redragonJS.alert(textStatus);
            }
        });
    }

    //设置查询功能
    var to = false;
    $('#searchTree').keyup(function() {
        if (to) {
            clearTimeout(to);
        }
        to = setTimeout(function() {
            var v = $('#searchTree').val();
            $('#jstree_div').jstree(true).search(v);
        }, 250);
    });

    //返回选择的节点id
    function getTreeSelectNodeId(){
        var selectId = $("#jstree_div").jstree(true).get_selected();
        return selectId.toString();
    }
</script>